<template>
    <div class="adver-campaign">
        <div class="main-head flex-between container-fluid">
            <div class="title">
                <h1 v-text="titleText"></h1>
            </div>
        </div>
        <div class="content container-fluid">
            <div class="breadcrumb">
                <a-breadcrumb :routes="routes">
                    <template slot="itemRender" slot-scope="{route, params, routes}">
                        <span v-if="routes.indexOf(route) === routes.length - 1">{{route.breadcrumbName}}</span>
                        <router-link v-else :to="`${route.path}`">{{route.breadcrumbName}}</router-link>
                    </template>
                </a-breadcrumb>
            </div>
            <div class="portlet">
                <a-spin :spinning="loading" size="large" :tip="$t('pro.public.loading')">
                    <a-form class="conditions grid" :form="form" layout="vertical">
                        <!-- Basic Settings 1开始 -->
                        <div class="grid-item ">
                            <div class="grid-item-title">
                                <h3 v-text="$t('pro.Editcampaigns.BasicSettings')"></h3>
                            </div>
                            <div class="grid-item-main">
                                <a-form-item :label="$t('pro.Editcampaigns.CampaignName')">
                                    <a-input
                                            :placeholder="$t('pro.Editcampaigns.CampaignNameTip')"
                                            v-decorator="[ 'campaigns.name', {
                                              rules: [{
                                                required: true, message: this.$t('pro.Editcampaigns.CampaignNameMess')
                                              }],
                                            }
                                          ]"
                                    />
                                </a-form-item>
                                <!--  开始日期 结束日期 -->
                                <a-form-item :label="$t('pro.Editcampaigns.DateTerm')">
                                    <a-range-picker
                                            style="width: 100%"
                                            v-decorator="['campaigns.date', {rangeConfig, initialValue: dateArr}]"
                                            format="YYYY-MM-DD"
                                    />
                                </a-form-item>

                                <a-form-item>
                                      <span slot="label">
                                          {{ $t('pro.Editcampaigns.AdDomain') }}&nbsp;
                                          <a-tooltip :title="$t('pro.formItem.advYm')">
                                            <a-icon type="question-circle-o"/>
                                          </a-tooltip>
                                    </span>
                                    <a-input
                                        :placeholder="$t('pro.Editcampaigns.AdDomainTip')"
                                        v-decorator="['campaigns.adDomain',{
                                          rules: [{
                                            required: true, message: $t('pro.Editcampaigns.AdDomainMess')
                                          },{validator: validateToDomain}],
                                        }
                                      ]"
                                    />
                                </a-form-item>
                                <!-- 地区 -->
                                <!--<a-form-item :label="$t('pro.Editcampaigns.Regions')">
                                    <a-select
                                            :placeholder="$t('pro.Editcampaigns.RegionsTip')"
                                            style="width: 100%"
                                            v-decorator="['campaigns.regions',{rules: [{
                                      required: true, message: $t('pro.Editcampaigns.RegionsMess')
                                    }],}]"
                                    >
                                      <a-select-option
                                              v-for="regions in regionsArr"
                                              :value="regions.iabId"
                                              :key="regions.iabId"
                                      >{{ regions.name }}</a-select-option>
                                    </a-select>
                                </a-form-item>-->

                                <!-- 交易所 -->
                                <!-- <a-form-item :label="$t('pro.Editcampaigns.Exchanges')">
                                   <a-select
                                           :placeholder="$t('pro.Editcampaigns.ExchangesTip')"
                                           mode="multiple"
                                           :tokenSeparators="[',']"
                                           style="width: 100%"
                                           v-decorator="['campaigns.exchanges']"
                                   >
                                     <a-select-option
                                             v-for="exchanges in exchangesArr"
                                             :value="exchanges.iabId"
                                             :key="exchanges.iabId"
                                     >{{exchanges.name}}</a-select-option>
                                   </a-select>
                                 </a-form-item>-->
                                <!--<a-form-item :label="$t('pro.Editcampaigns.Shard')">
                                  <a-input v-decorator="['campaigns.shard']"/>
                                </a-form-item>-->
                                <a-form-item>
                   <span slot="label">
                          {{ $t('pro.Editcampaigns.CampaignBudget') }}&nbsp;
                          <a-tooltip :title="$t('pro.formItem.advZJ')">
                            <a-icon type="question-circle-o"/>
                          </a-tooltip>
                    </span>
                                    <a-input-number
                                            @keydown="stopKeys"
                                            @change="handleBudget"
                                            style="width: 100%"
                                            :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                            :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                                            :min="0"
                                            :precision="2"
                                            v-decorator="[
                              'campaigns.totalBudget',
                              {
                                rules: [
                                { validator: validateSum },
                                {
                                  required: true, message:$t('pro.Editcampaigns.CampaignBudgetMess') ,
                                },{type:'number',message:$t('pro.Editcampaigns.NumberMess')}],
                              }
                           ]"
                                    />
                                </a-form-item>

                                <div class="dsp-form-group">
                                    <!--每天预算-->
                                    <a-form-item>
                    <span slot="label">
                          {{ $t('pro.Editcampaigns.DailyCap') }}&nbsp;
                          <a-tooltip :title="$t('pro.formItem.advMeiTian')">
                            <a-icon type="question-circle-o"/>
                          </a-tooltip>
                    </span>
                                        <a-input-number
                                                @change="handleDayBudget"
                                                @keydown="stopKeys"
                                                :min="0"
                                                :precision="2"
                                                style="width: 100%"
                                                :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                                :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                                                v-decorator="['campaigns.budgetLimitDaily',{rules:[{
                validator: validateDailyCap
              },{type:'number',message:$t('pro.Editcampaigns.NumberMess')}]}]"
                                        />
                                    </a-form-item>
                                    <!--每小时预算-->
                                    <a-form-item :label="$t('pro.Editcampaigns.Budgethourly')">
                                        <a-input-number
                                                @keydown="stopKeys"
                                                style="width: 100%"
                                                :min="0"
                                                :precision="2"
                                                :formatter="value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
                                                :parser="value => value.replace(/\$\s?|(,*)/g, '')"
                                                v-decorator="['campaigns.budgetLimitHourly',{rules:[{
                validator: validateBudgetHourly
              },{type:'number',message:$t('pro.Editcampaigns.NumberMess')}]}]"
                                        />
                                    </a-form-item>
                                </div>

                                <a-form-item :label="$t('pro.Editcampaigns.tb')">
                                    <a-radio-group v-decorator="['campaigns.targets.isTargets',{ initialValue: 1 }]" @change="tenderUsers">
                                        <a-radio :value="1">
                                            {{$t('pro.Editcampaigns.user1')}}
                                        </a-radio>
                                        <a-radio :value="0">
                                            {{$t('pro.Editcampaigns.user2')}}
                                        </a-radio>
                                    </a-radio-group>
                                    <a-button
                                            class="bs"
                                            style="margin-top: 10px"
                                            v-if="fromStatus !== ARCHIVED && isTargets !== 0"
                                            type="primary"
                                            html-type="submit"
                                            @click="handleSubmit($event,'jump')"
                                            v-text="submitText"></a-button>
                                </a-form-item>
                            </div>
                        </div>

                        <!-- Targeting Options 2开始 -->
                        <div v-show="isTargets === 0" class="grid-item">
                            <div class="grid-item-title">
                                <h3 v-text="$t('pro.Editcampaigns.TargetingOptions')"></h3>
                            </div>
                            <a-form-item>
                                <span slot="label">
                                        {{ $t('pro.Editcampaigns.by') }}
                                    <a-tooltip :title="$t('pro.Editcampaigns.byDocs')">
                                        <a-icon type="question-circle-o"/>
                                    </a-tooltip>
                                </span>
                                <a-switch v-decorator="['campaigns.targets.isMust', { valuePropName: 'checked' }]" />
                            </a-form-item>
                            
                            <div class="grid-item-main">
                                <!-- 性别 -->
                                <a-form-item :label="$t('pro.Editcampaigns.Gender')">
                                    <a-checkbox-group
                                            v-decorator="['campaigns.targets.userGender', { initialValue: ['F','M'] }]"
                                            style="width: 100%;"
                                            @change="handleSelect($event, 'userGender')"
                                    >
                                        <a-checkbox value="M">
                                            {{$t('pro.Editcampaigns.Male')}}
                                        </a-checkbox>
                                        <a-checkbox value="F">
                                            {{$t('pro.Editcampaigns.Female')}}
                                        </a-checkbox>
                                    </a-checkbox-group>
                                </a-form-item>

                                <!-- 年龄 -->
                                <a-form-item>
                                <span slot="label">
                                        {{ $t('pro.Editcampaigns.Agefrom') }}&nbsp;({{ageList[0]}} ~ {{ageList[1]}})&nbsp;
                                        <a-tooltip :title="$t('pro.formItem.ages')">
                                            <a-icon type="question-circle-o"/>
                                        </a-tooltip>
                                    </span>
                                    <div style="display: flex;align-items:center">
                                        <span class="dark-color-fff">0</span>
                                        <a-slider
                                                style="display: inline-block;width: 100%"
                                                range
                                                v-model="ageList"
                                                :tipFormatter="(Slider)=> `${$t('pro.Editcampaigns.age')}: ${Slider}`"
                                        />
                                        <span class="dark-color-fff">100</span>
                                    </div>
                                </a-form-item>

                                <!-- 升级版 ibs黑白 -->
                                <a-form-item>
                                    <span slot="label">
                                        {{ $t('pro.Editcampaigns.IABBlacklist') }}&nbsp;
                                        <a-tooltip :title="$t('pro.formItem.iab')">
                                            <a-icon type="question-circle-o"/>
                                        </a-tooltip>
                                    </span>
                                        <a-select
                                                class="b-r-none"
                                                v-decorator="['campaigns.targets.contentCategoriesIsInclude', { initialValue: '1' }]"
                                                style="width:25%;"
                                        >
                                            <a-select-option value="1">
                                                {{ $t('pro.Editcampaigns.include')}}
                                            </a-select-option>
                                            <a-select-option value="0">
                                                {{ $t('pro.Editcampaigns.onInclude')}}
                                            </a-select-option>
                                        </a-select>

                                        <a-tree-select
                                            :defaultExpandParent="false"
                                            @deselect="handleSelect($event, 'removeIAbSelect')"
                                            @click="isIbs = false"
                                            showSearch
                                            style="width: 75%"
                                            :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                                            :placeholder="$t('pro.Editcampaigns.IABTip')"
                                            allowClear
                                            multiple
                                            treeDefaultExpandAll
                                        
                                            @change="handleSelect($event, 'selectIAbList')"
                                            v-decorator="['campaigns.targets.contentCategories']"
                                        >
                                            <a-tree-select-node v-if="isIbs"></a-tree-select-node>
                                            <a-tree-select-node 
                                              v-else
                                              :value="os.all.title" 
                                              :title="os.all.title" 
                                              :key="key"
                                              v-for="(os,key) in getIbsList">
                                                    <a-tree-select-node 
                                                        :value="item.title" 
                                                        :title="item.title"
                                                        :key="item.name+index"
                                                        v-for="(item, index) in os.items"/>
                                            </a-tree-select-node>
                                        </a-tree-select>
                                </a-form-item>

                                <!-- 地理国家 -->
                                <a-form-item>
                                <span slot="label">
                                        {{ $t('pro.Editcampaigns.GeoCountry') }}&nbsp;
                                        <a-tooltip :title="$t('pro.formItem.guoj')">
                                            <a-icon type="question-circle-o"/>
                                        </a-tooltip>
                                    </span>
                                    <a-select
                                            class="b-r-none"
                                            v-decorator="['campaigns.targets.geoCountriesIsInclude', { initialValue: '1' }]"
                                            style="width:25%;"
                                    >
                                        <a-select-option value="1">
                                            {{ $t('pro.Editcampaigns.include')}}
                                        </a-select-option>
                                        <a-select-option value="0">
                                            {{ $t('pro.Editcampaigns.onInclude')}}
                                        </a-select-option>
                                    </a-select>

                                    <a-select
                                            :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                            showSearch
                                            :filterOption="filterOption"
                                            mode="multiple"
                                            allowClear
                                            style="width: 75%"
                                            :tokenSeparators="[',']"
                                            @change="handleSelect($event, 'selCountriesOptions')"
                                            @focus="isCountrier = false"
                                            v-decorator="['campaigns.targets.geoCountries']"
                                    >
                                        <a-select-option v-if="isCountrier" value="">default</a-select-option>
                                        <a-select-option
                                                v-else
                                                v-for="countriesOption in getCountriesOptions"
                                                :key="countriesOption.id"
                                                :value="countriesOption.commonName"
                                        >{{ countriesOption.commonName}}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>

                                <!-- 地理城市 -->
                                <!-- <a-form-item :label="$t('pro.Editcampaigns.GeoCity')">
                                <a-input
                                        :placeholder="$t('pro.Editcampaigns.GeoCityTip')"
                                        @change="handleInputChange"
                                        v-decorator="['campaigns.targets.geoRegion']"
                                />
                                </a-form-item>-->

                                <a-collapse :bordered="false" @change.once="openMap">
                                    <template v-slot:expandIcon="props">
                                        <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0"/>
                                    </template>
                                    <!--地图-->
                                    <a-collapse-panel :header="$t('pro.Editcampaigns.Location')" key="1"
                                                    :forceRender="true">
                                        <a-form-item :label="''">
                                            <div class="location">
                                                <div class="map" v-if="showMap">
                                                    <!-- 这里是地图 -->
                                                    <a-spin :spinning="mapPadding">
                                                        <div id="map-container"></div>
                                                    </a-spin>
                                                </div>
                                                <div style="margin: 20px 0">
                                                <a-radio-group
                                                        v-decorator="['campaigns.targets.geoIsInclude',{ initialValue: 1 }]"
                                                >
                                                    <a-radio :value="1">{{$t('pro.Editcampaigns.WhiteList')}}</a-radio>
                                                    <a-radio :value="0">{{$t('pro.Editcampaigns.BlackList')}}</a-radio>
                                                </a-radio-group>
                                                </div>
                                                <div class="manual">
                                                    <div class="dsp-form-group" :style="{'background': 'inherit'}">
                                                        <a-form-item :label="$t('pro.Editcampaigns.GPSlongitude')">
                                                            <a-input-number
                                                                    :precision="3"
                                                                    style="width: 100%"
                                                                    v-model="manualAreas.geoLongitude"
                                                                    @keydown="stopKeys"
                                                            />
                                                        </a-form-item>
                                                        <a-form-item :label="$t('pro.Editcampaigns.GPSlatitude')">
                                                            <a-input-number
                                                                    :precision="3"
                                                                    style="width: 100%"
                                                                    v-model="manualAreas.geoLatitude"
                                                                    @keydown="stopKeys"
                                                            />
                                                        </a-form-item>
                                                    </div>
                                                    <div class="dsp-form-group">
                                                        <a-form-item :label="$t('pro.Editcampaigns.GPSRadius')">
                                                            <a-input-number
                                                                    :precision="3"
                                                                    style="width: 100%"
                                                                    v-model="manualAreas.geoRange"
                                                                    @keydown="stopKeys"
                                                            />
                                                        </a-form-item>
                                                        <!-- 添加金纬度 按钮 -->
                                                        <a-form-item label="-" class="add-btn">
                                                            <a-button type="primary" @click="appendCurrent"
                                                                    v-text="$t('pro.admin.Add')"></a-button>
                                                        </a-form-item>
                                                    </div>
                                                </div>

                                                <div class="location-list" v-if="locationLists.length>0">
                                                    <a-table
                                                            bordered
                                                            :dataSource="locationLists"
                                                            :columns="colums"
                                                    >
                                                        <template slot="del" slot-scope="text, record">
                                                        <!-- <a-popconfirm
                                                                    v-if="locationLists.length"
                                                                    :title="$t('pro.Editcampaigns.DelMess')"
                                                                    @confirm="() => onDelete(record.key)"
                                                            >
                                                                <a href="javascript:;"
                                                                v-text="$t('pro.Editcampaigns.Del')"></a>
                                                            </a-popconfirm>-->
                                                            <a href="javascript:;" @click.stop="onDelete(record.key)"
                                                            v-text="$t('pro.Editcampaigns.Del')"></a>
                                                        </template>
                                                    </a-table>
                                                </div>
                                            </div>
                                        </a-form-item>
                                    </a-collapse-panel>

                                    <!--规则-->
                                    <a-collapse-panel :header="$t('pro.Editcampaigns.rules')" key="2">
                                        <a-form-item :label="''">
                                            <a-select
                                                    :placeholder="$t('pro.Editcampaigns.rulesTip')"
                                                    mode="multiple"
                                                    style="width: 100%"
                                                    :tokenSeparators="[',']"
                                                    @change="handleChange"
                                                    v-decorator="['campaigns.rtbStandardIds']"
                                            >
                                                <a-select-option
                                                        v-for="rules in rulesArr"
                                                        :value="rules.id"
                                                        :key="rules.id"
                                                >{{ rules.name }}
                                                </a-select-option>
                                            </a-select>
                                        </a-form-item>
                                    </a-collapse-panel>

                                    <!--过滤器-->
                                    <a-collapse-panel :header="$t('pro.Editcampaigns.Filterlist')" key="3"
                                                    :forceRender="true">
                                        <a-form-item>
                                            <a-radio-group
                                                    v-decorator="['campaigns.filterListType',{ initialValue: 'clear' }]"
                                                    @change="locationFuncChange2"
                                            >
                                                <a-radio value="clear">{{$t('pro.public.empty')}}</a-radio>
                                                <a-radio value="white">{{$t('pro.Editcampaigns.WhiteList')}}</a-radio>
                                                <a-radio value="black">{{$t('pro.Editcampaigns.BlackList')}}</a-radio>
                                            </a-radio-group>

                                            <a-select
                                                    :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                                    showSearch
                                                    :filterOption="filterOption"
                                                    style="width: 100%"
                                                    @change="handleChange($event,'country')"
                                                    v-decorator="['campaigns.filterListId']"
                                                    :disabled="filterDisabled"
                                            >
                                                <div slot="dropdownRender" slot-scope="menu">
                                                    <v-nodes :vnodes="menu"/>
                                                    <div style="padding: 8px; cursor: pointer;"
                                                        @click="destinationAddFilter">
                                                        <a-icon type="plus"/>
                                                        {{$t('pro.filterList.createFilterList')}}
                                                    </div>
                                                </div>

                                                <a-select-option
                                                        v-for="item in filterList"
                                                        :key="item.id"
                                                        :value="item.id"
                                                >{{ item.listName}}
                                                </a-select-option>
                                            </a-select>
                                        </a-form-item>
                                    </a-collapse-panel>
                                </a-collapse>
                            </div>
                        </div>
             
                       
                        <!-- Targeting Options 3开始 -->
                        <div v-show="isTargets === 0" class="grid-item">
                            <div class="grid-item-title">
                                <h3 v-text="$t('pro.Editcampaigns.MakeOptions')"></h3>
                            </div>
                            <div class="grid-item-main">
                                <a-form-item>
                                    <span slot="label">
                                            {{$t('pro.Editcampaigns.sspName')}}&nbsp;
                                            <a-tooltip :title="$t('pro.formItem.AdSsp')">
                                                <a-icon type="question-circle-o"/>
                                            </a-tooltip>
                                        </span>

                                    <a-select
                                            class="b-r-none"
                                            v-decorator="['campaigns.sspIsInclude', { initialValue: '1' }]"
                                            style="width:25%;"
                                    >
                                        <a-select-option value="1">
                                            {{ $t('pro.Editcampaigns.include')}}
                                        </a-select-option>
                                        <a-select-option value="0">
                                            {{ $t('pro.Editcampaigns.onInclude')}}
                                        </a-select-option>
                                    </a-select>

                                    <a-select
                                            :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                            mode="multiple"
                                            allowClear
                                            :filterOption="filterOption"
                                            style="width: 75%"
                                            v-decorator="['campaigns.ssp']"
                                    >
                                        <a-select-option
                                                v-for="devicetype in sspBindUserList"
                                                :disabled="!devicetype.isActive"
                                                :value="devicetype.id+''"
                                                :key="devicetype.id">
                                            {{ devicetype.name }}
                                        </a-select-option>
                                    </a-select>

                                </a-form-item>

                                <!--Make 品牌-->
                                <a-form-item>
                                    <span slot="label">
                                            {{ $t('pro.Editcampaigns.Make') }}&nbsp;
                                            <a-tooltip :title="$t('pro.formItem.make')">
                                                <a-icon type="question-circle-o"/>
                                            </a-tooltip>
                                        </span>
                                    <a-select
                                            class="b-r-none"
                                            v-decorator="['campaigns.targets.makeIsInclude', { initialValue: '1' }]"
                                            style="width:25%;"
                                    >
                                        <a-select-option value="1">
                                            {{ $t('pro.Editcampaigns.include')}}
                                        </a-select-option>
                                        <a-select-option value="0">
                                            {{ $t('pro.Editcampaigns.onInclude')}}
                                        </a-select-option>
                                    </a-select>

                                    <a-select
                                        :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                        mode="multiple"
                                        allowClear
                                        :filterOption="filterOption"
                                        style="width: 75%"
                                        @change="handleSelect($event, 'selectDeviceBrandList')"
                                        v-decorator="['campaigns.targets.make']"
                                    >
                                        <a-select-option
                                                v-for="devicetype in getDeviceBrandList"
                                                :value="devicetype.label"
                                                :key="devicetype.value">
                                            {{ devicetype.label }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>

                                <!-- 系统操作系统 -->
                                <a-form-item>
                                    <span slot="label">
                                            {{ $t('pro.Editcampaigns.SystemOS') }}&nbsp;
                                            <a-tooltip :title="$t('pro.formItem.os')">
                                                <a-icon type="question-circle-o"/>
                                            </a-tooltip>
                                        </span>
                                    <a-select
                                        class="b-r-none"
                                        v-decorator="['campaigns.targets.osIsInclude', { initialValue: '1' }]"
                                        style="width:25%;"
                                    >
                                        <a-select-option value="1">
                                            {{ $t('pro.Editcampaigns.include')}}
                                        </a-select-option>
                                        <a-select-option value="0">
                                            {{ $t('pro.Editcampaigns.onInclude')}}
                                        </a-select-option>
                                    </a-select>

                                    <a-tree-select
                                        @deselect="handleSelect($event, 'removeOsSelect')"
                                        showSearch
                                        style="width: 75%"
                                        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                                        :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                        allowClear
                                        multiple
                                        treeDefaultExpandAll
                                        @change="handleSelect($event, 'selectOsList')"
                                        v-decorator="['campaigns.targets.os']"
                                    >
                                        <a-tree-select-node :value="os.all.title" :title="os.all.title" :key="key"
                                                            v-for="(os,key) in getOsList">
                                            <a-tree-select-node :value="item.title" :title="item.title" :key="item.name"
                                                                v-for="item in os.items"/>
                                        </a-tree-select-node>
                                    </a-tree-select>

                                </a-form-item>

                                <a-form-item>
            
            
                                <span slot="label">
                                        {{ $t('pro.Editcampaigns.ws') }}&nbsp;
                                        <a-tooltip :title="$t('pro.formItem.ws')">
                                            <a-icon type="question-circle-o"/>
                                        </a-tooltip>
                                    </span>
                                    <a-select
                                        class="b-r-none"
                                        v-decorator="['campaigns.targets.browserIsInclude', { initialValue: '1' }]"
                                        style="width:25%;"
                                    >
                                        <a-select-option value="1">
                                            {{ $t('pro.Editcampaigns.include')}}
                                        </a-select-option>
                                        <a-select-option value="0">
                                            {{ $t('pro.Editcampaigns.onInclude')}}
                                        </a-select-option>
                                    </a-select>

                                    <a-select
                                        :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                        mode="multiple"
                                        allowClear
                                        :filterOption="filterOption"
                                        style="width: 75%"
                                        @change="handleSelect($event, 'selectBrowserList')"
                                        v-decorator="['campaigns.targets.browser']"
                                    >
                                        <a-select-option
                                                v-for="browser in getBrowserList"
                                                :value="browser.label"
                                                :key="browser.value">
                                            {{ browser.label }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>

                                <a-form-item>
                                <span slot="label">
                                        {{ $t('pro.Editcampaigns.wsl') }}&nbsp;
                                        <a-tooltip :title="$t('pro.formItem.lang')">
                                            <a-icon type="question-circle-o"/>
                                        </a-tooltip>
                                    </span>
                                    <a-select
                                        class="b-r-none"
                                        v-decorator="['campaigns.targets.deviceLanguageIsInclude', { initialValue: '1' }]"
                                        style="width:25%;"
                                    >
                                        <a-select-option value="1">
                                            {{ $t('pro.Editcampaigns.include')}}
                                        </a-select-option>
                                        <a-select-option value="0">
                                            {{ $t('pro.Editcampaigns.onInclude')}}
                                        </a-select-option>
                                    </a-select>
                                    <a-select
                                            :placeholder="$t('pro.Editcampaigns.GeoCountryTip')"
                                            mode="multiple"
                                            allowClear
                                            :filterOption="filterOption"
                                            style="width: 75%"
                                            :labelInValue="false"
                                            @change="handleSelect($event, 'selectDeviceLanguageList')"
                                            v-decorator="['campaigns.targets.deviceLanguage']"
                                    >
                                        <a-select-option
                                                v-for="(browser, index) in getDeviceLanguageList"
                                                :value="browser.label"
                                                :key="index">
                                            {{ browser.label }}
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>

                                <!--Model 产品型号-->
                                <!-- <a-form-item :label="$t('pro.Editcampaigns.Model')">
                                    <a-auto-complete
                                        :placeholder="$t('pro.Editcampaigns.ModelTip')"
                                        v-decorator="['campaigns.targets.model']"
                                        :dataSource="modelArr.names"
                                        :filterOption="filterOption"
                                        @select="selectComplete($event, 'modelArr', 'campaigns.targets.model')"
                                    />
                                </a-form-item>-->


                                <a-collapse :bordered="false">
                                    <template v-slot:expandIcon="props">
                                        <a-icon type="caret-right" :rotate="props.isActive ? 90 : 0"/>
                                    </template>
                                    <!-- 连接类型 -->
                                    <a-collapse-panel key="1" :forceRender="true">
                                        <span slot="header">
                                            {{ $t('pro.Editcampaigns.lineType') }}&nbsp;
                                            <a-tooltip :title="$t('pro.formItem.connect')">
                                                <a-icon type="question-circle-o"/>
                                            </a-tooltip>
                                        </span>
                                        <a-form-item :label="''">
                                            <a-checkbox :indeterminate="connectionAll.indeterminate"
                                                        :checked="connectionAll.checkedAll"
                                                        @change="onCheckAllChange($event,'connectTypeList','connectionAll','campaigns.targets.connectiontype')">
                                                {{$t('pro.admin.All')}}
                                            </a-checkbox>
                                            <a-checkbox-group style="width: 100%"
                                                            v-decorator="['campaigns.targets.connectiontype']">
                                                <div v-for="(item, index) in connectTypeList" :key="index">
                                                    <a-checkbox :value="item.value"
                                                                @change="onChange('campaigns.targets.connectiontype','connectTypeList', 'connectionAll')">
                                                        {{item.label}}
                                                    </a-checkbox>
                                                </div>

                                            </a-checkbox-group>
                                        </a-form-item>
                                    </a-collapse-panel>

                                    <!-- 设备类型 -->
                                    <a-collapse-panel :header="$t('pro.Editcampaigns.DeviceType')" key="2"
                                                    :forceRender="true">
                                        <a-form-item :label="''">
                                            <a-checkbox :indeterminate="deviceTypecheckAll.indeterminate"
                                                        :checked="deviceTypecheckAll.checkedAll"
                                                        @change="onCheckAllChange($event, 'devicetypeList','deviceTypecheckAll','campaigns.targets.devicetype')">
                                                {{$t('pro.admin.All')}}
                                            </a-checkbox>
                                            <a-checkbox-group style="width: 100%;"
                                                            v-decorator="['campaigns.targets.devicetype']">
                                                <div v-for="(item, index) in devicetypeList" :key="index">
                                                    <a-checkbox :value="item.value"
                                                                @change="onChange('campaigns.targets.devicetype', 'devicetypeList', 'deviceTypecheckAll')">
                                                        {{item.label}}
                                                    </a-checkbox>
                                                </div>
                                            </a-checkbox-group>
                                        </a-form-item>
                                    </a-collapse-panel>
                                </a-collapse>

                            </div>
                        </div>
                      

                        <!-- Submit Button   -->
                        <div>
                            <a-form-item>
                                <a-button
                                    class="bs"
                                    v-if="fromStatus !== ARCHIVED && isTargets === 0"
                                    type="primary"
                                    html-type="submit"
                                    @click="handleSubmit($event,'jump')"
                                    v-text="submitText"></a-button>
                            </a-form-item>
                        </div>
                    </a-form>
                </a-spin>
            </div>
        </div>

        <div class="content container-fluid" v-if="campaignId !== undefined">
            <creative-table ref="table" :campaignsId="String(campaignId)"></creative-table>
        </div>
    </div>
</template>

<script>
    //静态全局变量
    import {
        deviceBrandList,
        devicetypeList,
        connectTypeList,
        browserList,
        deviceLanguageList,
        osList,
        iabList
    } from '../../assets/JSdata/campaignOptions'
    import {mapConfig} from '../../config'
    import {stopKeys} from "@/assets/JSfunction";
    import {savaCampaigns, getCampaigns, updateCampaigns} from "@/api/campaigns";
    import {getAllDataByRule} from "@/api/rule-controller";
    import creativeTable from '@/components/common/creativeTable/creativeTable'
    import {ARCHIVED} from "../../utils/publicStatus"
    import {getBindUser} from "@/api/pulldown-data";
    import {getByTokenFilterList} from '../../api/filter-list'
    import moment from 'moment'
    import { validURL } from '../../utils/validate'

    let map;
    export default {
        moment,
        components: {
            creativeTable,
            VNodes: {
                functional: true,
                render: (h, ctx) => ctx.props.vnodes,
            },
        },
        data() {
            return {
                isIbs: true,
                isCountrier: true, // 国家
                
                isTargets: 1, //投标用户 是否自定义 1-所有用户
                //归档全局变量
                ARCHIVED,
                loading: false,
                defaultFilter: "",
                showMap: false,

                date: null,
                dateFormat: "YYYY-MM-DD HH:mm:ss",
                //时间提示
                rangeConfig: {
                    rules: [{required: true, message: this.$t('pro.Editcampaigns.DateTermMess')}],
                },
                dateArr: [this.$moment(moment().startOf('day'), 'YYYY-MM-DD'), this.$moment(moment().endOf('day'), 'YYYY-MM-DD')],//初始值
                form: this.$form.createForm(this),

                manualAreas: {
                    geoLongitude: null,
                    geoLatitude: null,
                    geoRange: null
                },
                filterDisabled: true,
                mapPadding: false,

                errors: {
                    country: "",
                    deviceLanguage: "",
                    geoCities: "",
                },

                ageList: [16, 62],

                fromStatus: null,
                makeValue: null,
                modelValue: null,

                iabCategories: [],
                selectIabCategories: [],
                countriesOptions: [], //国家
                selCountriesOptions: [],

                locationLists: [], //地图
                mapLang: undefined,

                regionsArr: [], //地区
                exchangesArr: [], //交易所
                rulesArr: [], //规则
                filterList: [],

                //产品型号
                modelArr: {
                    items: [],
                    names: []
                },

                osLists: JSON.parse(JSON.stringify(osList)),
                osListsCopy: JSON.parse(JSON.stringify(osList)),
                selectOsList: [],
                removeOsSelect: undefined,


                iabLists: JSON.parse(JSON.stringify(iabList)),
                iabListsCopy: JSON.parse(JSON.stringify(iabList)),
                selectIAbList: [],
                removeIAbSelect: undefined,

                connectTypeList,//連接类型
                connectionAll: {
                    indeterminate: false,
                    checkedAll: false,
                },
                devicetypeList, //设备类型
                deviceTypecheckAll: {
                    indeterminate: false,
                    checkedAll: false,
                },
                selectDeviceBrandList: [], //手机品牌
                selectBrowserList: [],//浏览器类型
                selectDeviceLanguageList: [],//浏览器语言
                browserList,
                deviceLanguageList,
                deviceBrandList,
                campBudget: null,
                dayBudget: null,
                userGender: [],
                sspBindUserList: [],
            };
        },
        computed: {
            colums() {
                return this.$t('pro.Editcampaigns.columns')
            },
            routes() {
                const routes = [
                    {
                        path: "/bidder/campaigns",
                        breadcrumbName: this.$t('pro.public.header.Campaigns')
                    },
                    {
                        path: "second",
                        breadcrumbName: this.$t('pro.Editcampaigns.CreateCampaign')
                    }
                ];
                return routes
            },

            campaignId() { return this.$route.params.id; },

            titleText() { return this.campaignId != null ? this.$t('pro.Editcampaigns.EditCampaign') : this.$t('pro.Editcampaigns.CreateCampaign') },

            submitText() { return this.campaignId != null ? this.$t('pro.Editcampaigns.SaveCampaign') : this.$t('pro.Editcampaigns.CreateCampaign') },

            getDeviceBrandList() { return this.deviceBrandList.filter(o => !this.selectDeviceBrandList.includes(o.label)) },

            getBrowserList() { return this.browserList.filter(o => !this.selectBrowserList.includes(o.label)) },

            getDeviceLanguageList() { return this.deviceLanguageList.filter(o => !this.selectDeviceLanguageList.includes(o.label)) },

            getIabCategories() {
                return this.iabCategories.filter(o => !this.selectIabCategories.includes(o.iabId));
            },
            getCountriesOptions() {
                return this.countriesOptions.filter(o => !this.selCountriesOptions.includes(o.commonName));
            },
            getOsList() {
                let olist = this.osLists; //静态变量
                let selectOsList = this.selectOsList || []; //已选中
                let flent;
                let spuerName;

                // 原生数据
                let osListsList = JSON.parse(JSON.stringify(this.osListsCopy));
                if (selectOsList.length > 0) {
                    for (let [key, value] of Object.entries(osListsList)) {
                        //All 被选择的时候
                        if (selectOsList.includes(value.all.title)) {
                            // 原始所有数据
                            let osListsListValue = osListsList[key].items;
                            osListsListValue.forEach(item => {
                                selectOsList = selectOsList.filter(im => {
                                    if (im !== item.title) {
                                        return true
                                    }
                                });
                            });
                            this.form.setFieldsValue({"campaigns.targets.os": selectOsList});
                            delete olist[key]
                        } else {
                            if (!!this.removeOsSelect) {
                                // 判断是否删除父类
                                //缓存没有选中项 需要给下拉框加回去 父
                                if (olist[key] == undefined) {
                                    olist[key] = value;
                                    this.removeOsSelect = undefined;
                                }
                            } else {
                                // 下拉里的数据
                                let olistValue = olist[key].items;

                                //查询子项有没有包括在选中里面 this.removeOsSelect;
                                olistValue.find((item, index) => {
                                    if (selectOsList.includes(item.title)) {
                                        olistValue.splice(index, 1); //子类删除
                                        flent = olistValue.length; //删除后儿子还有多少个
                                        spuerName = key;
                                        return true
                                    }
                                });
                            }
                        }
                    }
                    //判断删除子时  查看使用还有其他字类 子类全部删除时 进if 则 else
                    if (flent === 0) {
                        // 解除子类绑定值
                        this.osListsCopy[spuerName].items.forEach(item => {
                            //相对的不要
                            this.selectOsList = this.selectOsList.filter(item2 => item2 !== item.title);
                        });
                        // 添加父类
                        this.selectOsList.push(olist[spuerName].all.title);
                        this.form.setFieldsValue({'campaigns.targets.os': this.selectOsList})
                        // 删除下拉父类
                        delete olist[spuerName];
                    } else {
                        if (!!this.removeOsSelect) {
                            for (let [key, value] of Object.entries(osListsList)) {
                                // 原始所有数据
                                let osListsListTest = osListsList[key].items;
                                // 如果下拉数据不存在原始值，将原始值数据添加至下拉

                                //查询子项有没有包括在选中里面 this.removeOsSelect;
                                osListsListTest.find(item => {
                                    if (this.removeOsSelect === item.title) {
                                        olist[key].items.push(item);
                                        this.removeOsSelect = undefined;
                                        return true
                                    }
                                });
                            }
                        }
                    }
                } else {
                    olist = osListsList;
                    this.osLists = olist
                }
                return olist
            },

            getIbsList() {
                let olist = this.iabLists; //静态变量
                let selectIAbList = this.selectIAbList || []; //已选中
                let flent;
                let spuerName;
                // 原生数据
                let osListsList = JSON.parse(JSON.stringify(this.iabListsCopy));

                if (selectIAbList.length > 0) {
                    for (let [key, value] of Object.entries(osListsList)) {
                        //All 被选择的时候
                        if (selectIAbList.includes(value.all.title)) {
                            // 原始所有数据
                            let iabListsListValue = osListsList[key].items;
                            iabListsListValue.forEach((item) => {
                                selectIAbList = selectIAbList.filter((im) => {
                                    if (im !== item.title) {
                                        return true
                                    }
                                });
                            });
                            this.form.setFieldsValue({"campaigns.targets.contentCategories": selectIAbList});
                            delete olist[key]
                        } else {
                            if (!!this.removeIAbSelect) {
                                // 判断是否删除父类
                                //缓存没有选中项 需要给下拉框加回去 父
                                if (olist[key] == undefined) {
                                    olist[key] = value;
                                    this.removeIAbSelect = undefined;
                                }
                            } else {
                                // 下拉里的数据
                                let olistValue = olist[key].items;

                                //查询子项有没有包括在选中里面 this.removeOsSelect;
                                olistValue.find((item, index) => {
                                    if (selectIAbList.includes(item.title)) {
                                        olistValue.splice(index, 1); //子类删除
                                        flent = olistValue.length; //删除后儿子还有多少个
                                        spuerName = key;
                                        return true
                                    }
                                });
                            }
                        }
                    }
                    //判断删除子时  查看使用还有其他字类 子类全部删除时 进if 则 else
                    if (flent === 0) {
                        // 解除子类绑定值
                        this.iabListsCopy[spuerName].items.forEach(item => {
                            //相同的不要
                            this.selectIAbList = this.selectIAbList.filter(item2 => item2 !== item.title);
                        });
                        // 添加父类
                        this.selectIAbList.push(olist[spuerName].all.title);
                        this.form.setFieldsValue({'campaigns.targets.contentCategories': this.selectIAbList});
                        // 删除下拉父类
                        delete olist[spuerName];
                    } else {
                        if (!!this.removeIAbSelect) {
                            for (let [key] of Object.entries(osListsList)) {
                                // 原始所有数据
                                let osListsListTest = osListsList[key].items;
                                //查询子项有没有包括在选中里面 t
                                osListsListTest.find(item => {
                                    if (this.removeIAbSelect === item.title) {
                                        olist[key].items.push(item);
                                        this.removeIAbSelect = undefined;
                                        return true
                                    }
                                });
                            }
                        }
                    }
                } else {
                    olist = osListsList;
                    this.iabLists = olist
                }
                return olist
            },

            getMapLang() {
                //可选值：en，zh_en, zh_cn
                if (this.$i18n.locale === 'en') {
                    this.mapLang = 'en'
                } else {
                    this.mapLang = 'zh_cn'
                }
                return this.$i18n.locale != 'en' ? 'zh_cn' : 'en';
            }
        },
        watch: {
            getMapLang(newVal) {
                if (window.AMap) {
                    this.onApiLoaded();
                }
            },
            userGender(val, last) {
                this.$nextTick(() => {
                    //如果用户要全部取消了 执行下面处理
                    if (val.length <= 0) {
                        this.form.setFieldsValue({'campaigns.targets.userGender': last.length > 0 ? [last[0] || last[1]] : [val[0] || val[1]]});
                        this.userGender = last.length > 0 ? [last[0] || last[1]] : [val[0] || val[1]];
                    }
                })
            }
        },
        methods: {
            ss(){
              console.log(1234);
              
            },

            //简体是否自定义
            tenderUsers(e) {
                let { value } = e.target;
                this.isTargets = value;
            },
            validateToDomain(rule, value, callback) {
                if (value) {
                    if (validURL(value)) {
                        callback();
                    } else {
                        callback(this.$t("pro.Editcampaigns.suDomain"));
                    }
                } else {
                    callback();
                }
            },
            destinationAddFilter() {
                this.$router.push({path: '/bidder/filterlist/create'});
            },

            openMap(keys = []) {
                this.locationFuncChange({target: {value: 'map'}})
            },
            test(test) {
                console.log(test);
            },

            //根据已选择的值判断选项按钮
            onChange(key, list, obj, init = false) {
                this.$nextTick(() => {
                    let checkedList = this.form.getFieldValue(key) || [];
                    this[obj].indeterminate = !!checkedList.length && checkedList.length < this[list].length;
                    //是否初始化判断
                    this[obj].checkedAll = checkedList.length === this[list].length;
                })
            },

            /*
            * e = 按钮状态
            * list = 本地静态缓存
            * obj =  vue控制全选的变量
            * key = form表单的name字段
            * */
            onCheckAllChange(e, list, obj, key) {
                let flay = e.target.checked;
                this[obj].indeterminate = false;
                this[obj].checkedAll = flay;
                let allType = [];
                if (flay) {
                    allType = this[list].map(item => {
                        return item.value
                    });
                } else {
                    allType = [];
                }
                this.form.setFieldsValue({[key]: allType})
            },

            initCheckAll(list, obj, key) {
                this[obj].checkedAll = true;
                let allType = [];
                allType = this[list].map(item => {
                    return item.value
                });
                this.form.setFieldsValue({[key]: allType})
            },

            //选择要禁用的日期 配合时间控件的 :disabledDate事件一起使用
            disabledDate(current) {//禁用今天之前的日期
                // Can not select days before today and today
                return current <= moment().startOf('day') - 1;
            },
            //搜索
            filterOption(input, option) {
                return option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
            },
            //天
            handleDayBudget(value) {
                this.$nextTick(() => {
                    this.dayBudget = value
                })
            },
            //总
            handleBudget(value) {
                this.$nextTick(() => {
                    this.campBudget = value
                })
            },
            validateSum(rule, value, callback) {
                if (!!value) {
                    if(value <= this.dayBudget) {
                        callback(this.$t('pro.Editcampaigns.lessCampBudget'));
                    }/*else {
                        this.form.setFields({'campaigns.budgetLimitDaily': {error: [], value: this.dayBudget}})
                    }*/
                    //如果上面注释打开，然后提交按钮需要点击2次
                }
                callback()
            },

            validateDailyCap(rule, value, callback) {
                if (value) {
                    if (value >= this.campBudget) {
                        callback(this.$t('pro.Editcampaigns.lessCampBudget'));
                    } else {
                        this.form.setFields({'campaigns.budgetLimitHourly': {error: [], value: this.form.getFieldValue("campaigns.budgetLimitHourly")}})
                    }
                }
                callback()
            },

            validateBudgetHourly(rule, value, callback) {
                console.log('小时预算',value);
                if (!!value) {
                    if (value >= this.dayBudget) {
                        callback(this.$t('pro.Editcampaigns.lessDayBudget'));
                    }
                }
                callback()
            },

            stopKeys,

            //根据筛选的label数组 遍历所有下拉数据 取出对应的value|label
            arrayMapValue(arr, options, type = 'value') {
                let valuekey = [];
                arr.forEach(label => {
                    this[options].find(item2 => {
                        if (label === item2.label || label === item2.value || label === item2.commonName || label === item2.id || item2.iso316613LetterCode === label) {
                            valuekey.push(item2[type]);
                            return true
                        }
                    })
                });
                return valuekey;
            },

            ObjArrayForamt(select = [], Obj, type = 'value') {
                let valuekey = [];
                for (let [key, value] of Object.entries(this[Obj])) {
                    if (select.includes(value.all.title) || select.includes(value.all.name)) {
                        valuekey.push(value.all[type])
                    } else {
                        let {items} = value;
                        items.find(item => {
                            if (select.includes(item.title) || select.includes(item.name)) {
                                valuekey.push(item[type]);
                                return true
                            }
                        })
                    }
                }
                return valuekey
            },

            //创建广告活动的提交事件 提交之前会执行表单里自定义正则验证函数validator 在执行提交
            handleSubmit(e, status) {
                e.preventDefault();
                this.form.validateFields((err, values) => {
                    console.log(values);
                    if (err) {
                        const errors = err.campaigns.targets;
                        for (const key in errors) {
                            this.errors[key] = "error";
                        }
                    }
                    if (!err) {
                        try {
                            this.loading = !this.loading;
                            const obj = this.locationLists;
                            let gps = {};
                            // 经度
                            gps.geoLongitude = [];
                            // 纬度
                            gps.geoLatitude = [];
                            // 半径
                            gps.geoRange = [];
                            gps.mapID = [];
                            gps.key = [];
                            let i = 0;
                            for (let [key, value] of Object.entries(obj)) {
                                for (let [key, value] of Object.entries(value)) {
                                    gps[key][i] = value;
                                }
                                i++;
                            }

                            values.campaigns.activateTime = values.campaigns.date[0].format('YYYY-MM-DD') + " 00:00:00";
                            values.campaigns.expireTime = values.campaigns.date[1].format('YYYY-MM-DD') + " 23:59:59";

                            // GPS经度
                            values.campaigns.targets.geoLongitude = gps.geoLongitude.toString();
                            // GPS纬度
                            values.campaigns.targets.geoLatitude = gps.geoLatitude.toString();
                            // GPS半径
                            values.campaigns.targets.geoRange = gps.geoRange.toString();
                            const campaignId = this.campaignId;

                            //交易所
                            //values.campaigns.exchanges = this.handleIsEmptyexchanges(values.campaigns.exchanges, this.exchangesArr);
                            //地区
                            // values.campaigns.regions = this.handleIsEmptyregions(values.campaigns.regions, this.regionsArr);

                            //年龄范围
                            values.campaigns.targets.userAgeMin = this.ageList[0];
                            values.campaigns.targets.userAgeMax = this.ageList[1];

                            values.campaigns.targets.deviceLanguage = this.arrayMapValue(values.campaigns.targets.deviceLanguage || [], 'deviceLanguageList');
                            values.campaigns.targets.browser = this.arrayMapValue(values.campaigns.targets.browser || [], 'browserList');
                            values.campaigns.targets.make = this.arrayMapValue(values.campaigns.targets.make || [], 'deviceBrandList');
                            values.campaigns.targets.geoCountries = this.arrayMapValue(values.campaigns.targets.geoCountries || [], 'countriesOptions', 'iso316613LetterCode');

                            values.campaigns.targets.os = this.ObjArrayForamt(values.campaigns.targets.os || [], 'osListsCopy', 'name');
                            values.campaigns.targets.contentCategories = this.ObjArrayForamt(values.campaigns.targets.contentCategories || [], 'iabListsCopy', 'name');

                            values.campaigns.targets.isMust = +(!!values.campaigns.targets.isMust);
                            console.log('----提交参数----');
                            console.log(values.campaigns);

                            if (campaignId == null) {
                                savaCampaigns(JSON.stringify(values.campaigns))
                                    .then(res => {
                                        let newCampaignId = res.data.data
                                        values.campaigns.id = newCampaignId
                                        if (res.data.code === "200" && res.data.data) {
                                            this.$message.success(this.$t('pro.Editcampaigns.operationSuccess'), 1).then(() => {
                                                if (status == "jump") {
                                                    this.$store.commit("changeCampaigns", values.campaigns);

                                                    //需要跳到新的广告详情编辑页
                                                    this.$router.push("/bidder/editcreative/campaignid/" + newCampaignId);
                                                    this.$message.info(this.$t('pro.Editcampaigns.CampaigncreatedMess'))
                                                }
                                                if (status == "refresh") {
                                                    this.loading = !this.loading;
                                                    this.locationLists = [];
                                                    this.manualAreas = {
                                                        geoLongitude: null,
                                                        geoLatitude: null,
                                                        geoRange: null
                                                    };
                                                    this.date = null;
                                                    this.form.resetFields();
                                                }
                                            });
                                        }
                                    }).finally(() => {
                                    this.loading = !this.loading;//关闭动画
                                })
                            } else {
                                values.campaigns.id = campaignId;
                                updateCampaigns(values.campaigns)
                                    .then(res => {
                                        if (res.data.code == '200') {
                                            //修改后重新获取新的vuex CampaignList列表
                                            this.$store.dispatch('GetCampaignList', false)
                                            this.$message.success(this.$t('pro.Editcampaigns.operationSuccess'), 1).then(() => {
                                                if (status == "jump") {
                                                    this.$store.commit("changeCampaigns", values.campaigns);
                                                    this.$router.push("/bidder/campaigns");
                                                }
                                                if (status == "refresh") {
                                                    this.date = null;
                                                    this.form.resetFields();
                                                }
                                            });
                                        }
                                    })
                                    .finally(() => {
                                        this.loading = false;//关闭动画
                                    })
                            }

                        } catch (e) {
                            console.log(e)
                        }
                    }
                });
            },

            //用于记录用户选择那些项，然后从下拉中删除 公共方法 111
            handleSelect(value, target = "") {
                this[target] = value;
            },

            handleChange(value, target = "") {
                if (target) {
                    this.errors[target] = "";
                }
                console.log(value);
            },

            // 切换手动输入地理坐标和地图选择坐标
            locationFuncChange(e) {
                this.showMap = e.target.value === "map";
                this.manualAreas.geoLongitude = null;
                this.manualAreas.geoLatitude = null;
                this.manualAreas.geoRange = null;
                if (this.showMap) {
                    if (window.AMap) {
                        this.mapPadding = true;
                        setTimeout(() => {
                            this.onApiLoaded();
                        },2500)
                    }
                }
                this.$nextTick(() => {
                    console.log(this.$el.querySelector('#map-container'));
                })
            },

            //过滤器判断是否清空
            locationFuncChange2(e = {}) {
                let {value} = e.target || {value: this.form.getFieldValue('campaigns.filterListType') || "clear"};
                if ('clear' === value) {
                    this.form.setFieldsValue({'campaigns.filterListId': ""});
                    this.filterDisabled = true
                } else {
                    this.filterDisabled = false
                }
            },
            //判断地区是否为空
            handleIsEmptyregions(obj, objArr) {
                if (obj !== undefined) {
                    obj = obj.toString();
                    let exchangeArr = [];
                    let exchangeCode = obj.split(',');
                    exchangeCode.forEach(keys => {
                        objArr.forEach(item => {
                            if (keys == item.iabId || keys === item.name) {
                                exchangeArr.push(item.iabId)
                            }
                        })
                    })
                    return exchangeArr.join()
                    // valueTarget.os = JSON.parse(valueTarget.os).value.join(',')
                }
            },

            //判断交易所是否为空
            handleIsEmptyexchanges(obj, objArr) {
                if (obj !== undefined) {
                    obj = obj.toString();
                    let exchangeArr = [];
                    let exchangeCode = obj.split(',');
                    exchangeCode.forEach(keys => {
                        objArr.forEach(item => {
                            if (keys == item.iabId || keys === item.name) {
                                exchangeArr.push(item.iabId)
                            }
                        })
                    });
                    return exchangeArr.join()
                    // valueTarget.os = JSON.parse(valueTarget.os).value.join(',')
                }
            },

            //处理地区的显示
            regionsDisplay(value) {
                let that = this
                if (value !== undefined) {
                    let regionsArr = []
                    let regionsCode = value.split(',');
                    regionsCode.forEach(keys => {
                        that.regionsArr.forEach(item => {
                            if (keys == item.iabId || keys == item.name) {
                                regionsArr.push(item.name)
                            }
                        })
                    })
                    return value = regionsArr
                }
            },

            //处理交易所的显示
            exchangesDisplay(value) {
                let that = this
                if (value !== undefined) {
                    let exchangeArr = []
                    let exchangeCode = value.split(',');
                    exchangeCode.forEach(keys => {
                        that.exchangesArr.forEach(item => {
                            if (keys == item.iabId || keys == item.name) {
                                exchangeArr.push(item.name)
                            }
                        })
                    })
                    return value = exchangeArr
                }
            },

            //处理国家的显示
            countryDisplay(value) {
                if (value !== undefined) {
                    //处理国家的显示
                    let countryArr = [];
                    let countryCode = [];
                    if (typeof value === 'string' || typeof value === 'number') {
                        countryCode = this.toStrArrFormat(value);
                    } else {
                        countryCode = JSON.parse(value);
                    }
                    countryCode.forEach(keys => {
                        this.countriesOptions.forEach(item => {
                            if (keys == item.id || keys === item.commonName || keys === item.iso316613LetterCode) {
                                countryArr.push(item.commonName)
                            }
                        })
                    });

                    return countryArr
                }
            },
            // 添加异步请求脚本 地图
            addMapScript() {
                let { mapKey } = mapConfig || {};
                let src1 = `https://webapi.amap.com/maps?v=1.4.15&key=${mapKey}&plugin=AMap.Autocomplete,AMap.PlaceSearch,AMap.CircleEditor`;
                let s1 = document.createElement("script");
                s1.setAttribute("src", src1);
                document.head.appendChild(s1);
            },
            // 实例化地图
            onApiLoaded() {
                this.$nextTick(() => {
                    map = new AMap.Map("map-container", {
                        zoom: 12,
                        lang: this.mapLang || this.getMapLang, //可选值：en，zh_en, zh_cn
                    });
                    console.log("window.AMap:" + window.AMap);
                    // 添加插件
                    let Autocomplete = new AMap.Autocomplete();
                    let PlaceSearch = new AMap.PlaceSearch();
                    map.addControl(Autocomplete);
                    map.addControl(PlaceSearch);

                    let drawPoint, circleEditor;
                    const _this = this;
                    const showInfoClick = e => {
                        drawPoint = [e.lnglat.getLng(), e.lnglat.getLat()];
                        this.manualAreas.geoLongitude = e.lnglat.getLng();
                        this.manualAreas.geoLatitude = e.lnglat.getLat();
                        this.manualAreas.geoRange = 1000;
                        //geoRange: null
                        drawer(drawPoint);
                    };

                    // 事件绑定
                    const clickOn = () => {
                        map.on("click", showInfoClick);
                    };
                    clickOn();

                    // 解绑事件
                    function clickOff() {
                      map.off("click", showInfoClick);
                    }

                    var autoOptions = {
                        input: "tipinput"
                    };
                    var auto = new AMap.Autocomplete(autoOptions);
                    var placeSearch = new AMap.PlaceSearch({
                        map: map
                    }); //构造地点查询类
                    AMap.event.addListener(auto, "select", select); //注册监听，当选中某条记录时会触发
                    const select = e => {
                        placeSearch.setCity(e.poi.adcode);
                        placeSearch.search(e.poi.name); //关键字查询查询
                    };
                    let that = this;

                    function drawer(drawPoint) {
                        var circle = new AMap.Circle({
                            center: drawPoint,
                            geoRange: 1000, //半径
                            borderWeight: 3,
                            strokeColor: "#FF33FF",
                            strokeWeight: 6,
                            strokeOpacity: 0.2,
                            fillOpacity: 0.4,
                            strokeStyle: "dashed",
                            strokeDasharray: [10, 10],
                            // 线样式还支持 'dashed'
                            fillColor: "#1791fc",
                            zIndex: 50
                        });
                        circle.setMap(map);

                        // 缩放地图到合适的视野级别
                        map.setFitView([circle]);
                        circleEditor = new AMap.CircleEditor(map, circle);
                        circleEditor.open();
                        circleEditor.on('adjust', function (event) {
                            that.manualAreas.geoRange = event.radius
                        });

                        //clickOff() 只能点击一次

                        circleEditor.on("end", function (event) {
                            // event.target 即为编辑后的圆形对象
                            let area = {
                                geoLongitude: event.target.He.center.lng,
                                geoLatitude: event.target.He.center.lat,
                                geoRange: event.target.He.radius / 1000,
                                mapID: event.target._amap_id
                            };

                            const appendCurrent = _this.locationLists.every(
                                current => current.mapID != area.mapID
                            );
                            if (appendCurrent) {
                                let addKey;
                                if (_this.locationLists.length == 0) {
                                    if (_this.locationLists.length == 0) {
                                        addKey = 0;
                                    } else {
                                        addKey =
                                            Number(
                                                _this.locationLists[_this.locationLists.length - 1].key
                                            ) + 1;

                                    }
                                    area.key = `${addKey}`;
                                    addKey++;
                                    console.log(addKey);
                                    _this.locationLists.push(area);
                                } else {
                                    return
                                }
                            }
                        });
                        // 事件委托，若未生成button则无此事件
                        let mapWrap = document.querySelector(".map");
                        mapWrap.addEventListener("click", e => {
                            if (e.target.id == "add_btn") {
                                circleEditor.close();
                            }
                        });
                    }

                    //停止加载
                    this.mapPadding = false
                });
            },

            onDelete(key) {
                const dataSource = [...this.locationLists];
                this.locationLists = dataSource.filter(item => item.key !== key);
            },

            // 人工输入经纬度添加覆盖范围
            appendCurrent() {
                if (this.manualAreas) {
                    this.manualAreas.geoLatitude = Math.floor(this.manualAreas.geoLatitude * 1000) / 1000;
                    this.manualAreas.geoLongitude = Math.floor(this.manualAreas.geoLongitude * 1000) / 1000;
                }
                let areasValues = Object.values(this.manualAreas);
                const append = areasValues.every(value => value != null);

               
                if (append) {
                    let addKey;
                    if (this.locationLists.length == 0) {
                        addKey = 0;
                        this.manualAreas.key = `${addKey}`;
                        let manualAreas = JSON.parse(JSON.stringify(this.manualAreas));
                        this.locationLists.push(manualAreas);
                    } else {
                        addKey = Number(this.locationLists[this.locationLists.length - 1].key) + 1;
                        this.manualAreas.key = `${addKey}`;
                        let manualAreas = JSON.parse(JSON.stringify(this.manualAreas));
                        this.locationLists.push(manualAreas);
                    }
                     //清除所有遮盖
                    map.clearMap();
                    this.manualAreas.geoLatitude = null;
                    this.manualAreas.geoLongitude = null;
                    this.manualAreas.geoRange = null
                }
            },


            toStrArrFormat(value) {
                return value.toString().split(",");
            }
        },

        beforeCreate() {
            getAllDataByRule().then(res => {
                this.rulesArr = res.data.data
            });

            //过滤器
            getByTokenFilterList().then(res => {
                let {data} = res.data || {};
                this.filterList = data || []
            });

            this.$store.dispatch('GetIabCategories').then(res => {
                this.iabCategories = res;
            });

            this.$store.dispatch('GetCountries').then(res => {
                this.countriesOptions = res;
            });
        },

        created() {
            //初始化
            if (this.campaignId != null) {
                this.routes[1].breadcrumbName = this.$t('pro.Editcampaigns.EditCampaign')
                this.loading = !this.loading; //开启加载动画
                let parameter = "/" + this.campaignId;
                getCampaigns(parameter).then(res => {
                    const {code, data} = res.data;

                    this.dateArr = [this.$moment(data.activateTime, 'YYYY-MM-DD'), this.$moment(data.expireTime, 'YYYY-MM-DD')]

                    this.form = this.$form.createForm(this, {
                        // 当Form.Item子节点的值发生改变时触发，可以把对应的值转存到 Redux store
                        //onFieldsChange: (_, changedFields) => {},
                        // 把 props 转为对应的值，可用于把 Redux store 中的值读出,可以在此给form赋值
                        mapPropsToFields: () => {
                            let that = this;
                            const obj = res.data.data;
                            this.$store.commit("changeCampaigns", obj);
                            this.fromStatus = obj.status;

                            if (!obj) return;
                            let data = {};
                            data.campaigns = {};
                            data.campaigns.targets = {};
                            // 地图
                            if (obj.targets.geoLatitude) {
                                const geoLatitude = obj.targets.geoLatitude.split(",");
                                const geoLongitude = obj.targets.geoLongitude.split(",");
                                const geoRange = obj.targets.geoRange.split(",");
                                let locationLists = [];
                                for (let j = 0; j < geoLatitude.length; j++) {
                                    locationLists[j] = {};
                                    locationLists[j].key = j;
                                    locationLists[j].geoLatitude = geoLatitude[j];
                                    locationLists[j].geoLongitude = geoLongitude[j];
                                    locationLists[j].geoRange = geoRange[j];
                                }
                                this.locationLists = locationLists;
                            }
                            let date = [];
                            this.ageList = [];

                            for (let [key, value] of Object.entries(obj)) {
                                if (value == null) continue;
                                if (key == "activateTime") {
                                    date[0] = this.$moment(value);
                                }
                                if (key == "expireTime") {
                                    date[1] = this.$moment(value);
                                }
                                if (key == 'totalBudget') {
                                    this.campBudget = value
                                }
                                if (key == 'budgetLimitDaily') {
                                    this.dayBudget = value
                                }
                                //地区
                                if (key == "regions") {
                                    value = this.regionsDisplay(value)
                                }
                                if (key == "ssp") {
                                    let val =""+value;
                                    value = val.split(",")
                                }
                                //交易所
                                if (key == "exchanges") {
                                    value = this.exchangesDisplay(value)
                                }
                                // ssp的是否选中判断
                                if (key == "sspIsInclude") {
                                    value = value+"";
                                }
                                if (key == "targets") {
                                    // value.os = this.osDisplay(value.os)
                                    for (let [targetsKey, targetsValue] of Object.entries(value)) {
                                        if (targetsValue == null) continue;

                                        try {
                                            value = JSON.parse(targetsValue);
                                        } catch (error) {
                                            value = targetsValue;
                                        }

                                        if (typeof value == "object") {
                                            let targetObject = value;
                                            data.campaigns.targets[targetsKey] = {};
                                            try {
                                                for (let [targetKey, targetValue] of Object.entries(targetObject)) {
                                                    if (targetValue == null) continue;
                                                    value = targetValue;
                                                    data.campaigns.targets[targetsKey][targetKey] = this.$form.createFormField({value});
                                                }
                                            } catch (error) {
                                                console.log(error);
                                            }
                                        } else {

                                            switch (targetsKey) {
                                                case 'userGender':
                                                case 'devicetype':
                                                case 'connectiontype':
                                                case 'userGender':
                                                    //字符串数组 转 真数组
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({'value': this.toStrArrFormat(value)});
                                                    break;
                                                case 'deviceLanguage':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({
                                                        'value':
                                                            this.arrayMapValue(this.toStrArrFormat(value), 'deviceLanguageList', 'label')
                                                    });
                                                    break;
                                                //多选 层级
                                                case 'os':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({
                                                        'value':
                                                            this.ObjArrayForamt(this.toStrArrFormat(value), 'osListsCopy', 'title')
                                                    });
                                                    break;
                                                case 'contentCategories':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({
                                                        'value':
                                                            this.ObjArrayForamt(this.toStrArrFormat(value), 'iabListsCopy', 'title')
                                                    });
                                                    break;
                                                case 'browser':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({
                                                        'value':
                                                            this.arrayMapValue(this.toStrArrFormat(value), 'browserList', 'label')
                                                    });
                                                    break;
                                                case 'make':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({
                                                        'value':
                                                            this.arrayMapValue(this.toStrArrFormat(value), 'deviceBrandList', 'label')
                                                    });
                                                    break;
                                                case 'userAgeMin':
                                                    this.ageList.unshift(+value);
                                                    break;
                                                case 'userAgeMax':
                                                    this.ageList.push(+value);
                                                    break;
                                                case 'geoCountries':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({'value': this.countryDisplay(value)});
                                                    break;
                                                case 'isTargets':
                                                    this.isTargets = value;
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({value});
                                                    break;
                                                case 'isMust':
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({value: !!value});
                                                    break;
                                                case 'geoIsInclude':
                                                    //转为数据类型
                                                    data.campaigns.targets[targetsKey] = this.$form.createFormField({value: value});
                                                    break;

                                                default:
                                                    let flay = targetsKey.endsWith('IsInclude');
                                                    if (flay){
                                                        data.campaigns.targets[targetsKey] = this.$form.createFormField({value: value+""});
                                                    }else {
                                                        data.campaigns.targets[targetsKey] = this.$form.createFormField({value});
                                                    }
                                            }


                                        }
                                    }
                                } else {
                                    data.campaigns[key] = this.$form.createFormField({value});
                                }
                            }
                            this.date = date;
                            return data;
                        },
                        // 任一表单域的值发生改变时的回调
                        onValuesChange: (_, values) => {
                        }
                    });

                    //回写
                    this.$nextTick(() => {
                        this.selectDeviceBrandList = this.form.getFieldValue('campaigns.targets.make') || [];
                        this.selectBrowserList = this.form.getFieldValue('campaigns.targets.browser') || [];
                        this.selectDeviceLanguageList = this.form.getFieldValue('campaigns.targets.deviceLanguage') || [];
                        this.selCountriesOptions = this.form.getFieldValue('campaigns.targets.geoCountries') || [];

                        this.selectIAbList = this.form.getFieldValue('campaigns.targets.contentCategories') || [];
                        this.selectOsList = this.form.getFieldValue('campaigns.targets.os') || [];

                        //查询是否全选
                        this.onChange('campaigns.targets.devicetype', 'devicetypeList', 'deviceTypecheckAll', true);
                        this.onChange('campaigns.targets.connectiontype', 'connectTypeList', 'connectionAll', true);
                        ////判断是否禁用过滤
                        this.locationFuncChange2();
                    })
                })
                    .finally(() => {
                        this.loading = !this.loading;//关闭动画
                    })
            } else {
                //新增进入
                this.$nextTick(() => {
                    //是新增的时候 显示全选
                    this.initCheckAll('connectTypeList', 'connectionAll', 'campaigns.targets.connectiontype');
                    this.initCheckAll('devicetypeList', 'deviceTypecheckAll', 'campaigns.targets.devicetype');
                })
            }

            //查询绑定bid用户
            getBindUser().then(res => {
                let {code, data} = res.data || {}
                if(code == 200) {
                    data = data || [];
                    this.sspBindUserList = data.map(item => {
                        return {
                            id: item.id,
                            isActive: item.isActive,
                            name: `${item.region}[${item.name}]`,
                        }
                    })
                }

            })

        },
        beforeMount() {
            //加载地图js
            this.addMapScript();
        },
        destroyed() {
            //离开销毁地图
            map && map.destroy();
        }
    };
</script>

<style scoped>
    .location-list {
        overflow: auto;
        max-width: 99.99%;
    }

    #map-container {
        width: 100%;
        height: 300px;
    }

    .content.container-fluid {
        min-height: 0;
    }
</style>

<style lang="less">

    // <覆盖ant design css
    .ant-table-thead > tr > th,
    .ant-table-tbody > tr > td {
        padding: 16px 8px;
    }

    .ant-form-item-children {
        width: 100%;
        height: 100%;
        display: block;
        > span {
            width: 100%;
        }
    }

    // 选择日期组件样式小屏设备中重置
    @media screen and (max-width: 700px) {
        .ant-calendar-range {
            width: 77vw;
            left: 50%;
            transform: translateX(-50%);
        }

        .ant-calendar-date-panel {
            display: flex;
            flex-direction: column;
        }

        .ant-calendar-range-part {
            width: 100%;
        }
    }

    // 覆盖ant design css>
    h1,
    h3 {
        margin-bottom: 0;
    }

    .buttongrid {
        justify-items: end;
        display: grid;
    }

    .Creativesgrid {
        width: 100%;
        grid-template-columns: 50% 47%;
    }

    .selectCreatives {
        grid-template-columns: repeat(3, auto);
    }

    .form-group {
        margin-bottom: 10px;
    }

    .conditions.grid {
        grid-gap: 20px;
        grid-template-columns: repeat(3, 1fr);
    }

    .conditions > div:nth-child(3) .grid-item-title {
        border-bottom: 1px solid #c2cad8;
    }

    .ant-form-item-children > span.ant-calendar-picker {
        width: 100%;
    }

    @media screen and (max-width: 992px) {
        .conditions.grid {
            // grid-gap: 20px;
            grid-template-columns: repeat(2, 1fr);
            .grid-item:nth-child(1) {
                grid-row: 1;
                grid-column: 1;
            }
            .grid-item:nth-child(2) {
                grid-row: 2;
                grid-column: 1;
            }
            .grid-item:nth-child(3) {
                grid-row: 2;
                grid-column: 2;
            }
            .grid-item:nth-child(4) {
                grid-row: 3;
                grid-column: 1;
            }
        }
    }

    @media screen and (max-width: 768px) {
        .conditions.grid {
            // grid-gap: 20px;
            grid-template-columns: 1fr;
            .grid-item {
                grid-column: 1 !important;
            }
            .grid-item:nth-child(1) {
                grid-row: 1;
            }
            .grid-item:nth-child(2) {
                grid-row: 2;
            }
            .grid-item:nth-child(3) {
                grid-row: 3;
            }
            .grid-item:nth-child(4) {
                grid-row: 4;
            }
        }
    }

    .dsp-form-group-mini {
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-gap: 5px;
        .ant-input-number {
            width: 100%;
        }
    }
</style>
